<?php
class JqGrid{
	public static function getData($option){
		$page = Yii::app()->request->getParam("page",1);
		$rows = Yii::app()->request->getParam("rows",0);
		$sortCol = Yii::app()->request->getParam("sidx","");
		$sortOrder = Yii::app()->request->getParam("sord","");
		$search = Yii::app()->request->getParam("search","");
		
		if (isset($option["select"])){
			$strSelect = $option["select"];
		}else{
			throw new Exception("Select Can't be empty");			
		}
		
		if (isset($option["from"])){
			$strFrom = $option["from"];
		}else{
			throw new Exception("from Can't be empty");
		}
		
		$ssql = "select $strSelect from $strFrom ";
		$ssql2 = "select count(*) as ttlRow from $strFrom ";
		
		
		if (isset($option["where"])){
			$strWhere = $option["where"];
		}else{
			$strWhere = " true";
		}
		//echo $ssql ."</br>";
		 
		$ssql .= " where " . $strWhere;
		$ssql2 .= " where " . $strWhere;
		
		
		$arrSearch = array();
		if (isset($option["search"])){
			$arrSearch = $option["search"];
		}				
		$strTmp =" and (";
		foreach ($arrSearch as $srcField){
			$strTmp .=  $srcField . " like :srcString or ";
		}
		$strTmp = rtrim($strTmp,"or ");
		
		$strTmp .=")";		
		$strTmp = rtrim($strTmp);
		
		if (substr($strTmp,strlen($strTmp) - 7) == " and ()" ){
			$strTmp = substr($strTmp,0,strlen($strTmp) - 7);
		}
		
		
		
		$ssql .= $strTmp;
		$ssql2 .= $strTmp;
		//echo $ssql;
		//exit;
		
		//$strGroup = $option["group"];
		$offset = ($page - 1) * $rows;
		$ssql .= " limit $rows offset $offset";
		$params = array();
		if (isset($option["params"])){;
			$params = $option["params"];
		}
		
		$params[":srcString"] = "%$search%";
		
		$conn = Yii::app()->db;
		$cmd2 = $conn->createCommand($ssql2);
		$result = $cmd2->queryRow(true,$params);
		$ttlRow = $result["ttlRow"];
		$cmd = $conn->createCommand($ssql);
		$result = $cmd->queryAll(true,$params);
		$totalPage =  ceil($ttlRow /$rows);
		$jGridData = array();
		$jGridData["total"] = $totalPage;
		$jGridData["page"] = $page;
		$jGridData["records"] = $ttlRow;
		$rows = $result;
		//for($i =0;$i < 100;$i++){
		//	$row = array();
		//	$row["id"] = $i;
		//	$row["nama"] = "Nama " . $i;
		//	$row["umur"] = rand(20,50);
		//	$rows[] = $row;
		//}
		$jGridData["rows"] = $rows;
		return $jGridData;
		
		
		
		
	}
}